package com.ruoyi.web.controller.system;

import java.util.*;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 测试登录
     *
     * @return 结果
     */
    @GetMapping("/testlogin")
    public AjaxResult testLogin() {
        return AjaxResult.success().setData("Bearer " + loginService.testLogin("Fjun", "o44rc4"));
    }

    /**
     * 微信登录方法
     *
     * @param user 微信小程序用户
     * @return 结果
     */
    @PostMapping("/wxlogin")
    public AjaxResult wxlogin(@Validated @RequestBody SysUser user) {
        AjaxResult ajax = AjaxResult.success();
        if (user.getCode().isEmpty()) {
            ajax.put(Constants.CODE, -1);
            return ajax;
        }
        // 获取Openid
        String openid = loginService.getOpenid(user.getCode(), Constants.BX_ID, Constants.BX_SECRET);
        // 用户验证
        SysUser selectUser = iSysUserService.selectUserByOpenid(openid);
        String token;
        if (selectUser == null) {
            if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                    && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            }
            user.setPassword(SecurityUtils.encryptPassword(openid.substring(0, 6)));
            user.setOpenid(openid);
            user.setStatus("0");
            user.setDeptId(101L);
            user.setBalance(0F);
            user.setRoleIds(new Long[]{3L});
            user.setRemark("小程序用户");
            ajax.put(Constants.CODE, userService.insertUser(user));
            ajax.put(Constants.USER, user);
            token = loginService.wxlogin(user.getUserName(), openid.substring(0, 6), openid);
        } else {
            ajax.put(Constants.CODE, 0);
            ajax.put(Constants.USER, selectUser);
            token = loginService.wxlogin(selectUser.getUserName(), openid.substring(0, 6), openid);
        }

        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
